package com.donger.sso.login.service;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.common.core.utils.BizException;
import com.donger.sso.login.entity.LoginData;
import com.donger.sso.system.entity.SysAdmin;
import com.donger.sso.system.service.SysAdminService;
import io.vavr.control.Try;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginService {

    private final static PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Autowired
    private SysAdminService sysAdminService;


    /**
     * 用户名密码登陆
     *
     * @param username
     * @param password
     * @return
     */
    public LoginData loginByUsername(String username, String password) {

        Try<SysAdmin> sysAdmins = Try.of(() -> {
            // 只查询管理员，其他用户不能使用改功能登陆
            return sysAdminService.getOne(Wrappers.<SysAdmin>lambdaQuery()
                    .eq(SysAdmin::getUsername, username)
                    .eq(SysAdmin::getStatus, "Y")
            );
        });
        if (sysAdmins.isFailure()) {
            throw new BizException("查询用户失败或用户被锁定");
        }
        SysAdmin sysAdmin = sysAdmins.get();
        Boolean booleans = checkPassword(sysAdmin, password);
        if (!booleans) {
            throw new BizException("用户名或密码错误");
        }

        // 进行登陆
        StpUtil.login(sysAdmin.getId());

        String tokenValue = StpUtil.getTokenValue();
        return LoginData.builder()
                .phone(sysAdmin.getPhone())
                .token(tokenValue)
                .userId(sysAdmin.getId())
                .userName(sysAdmin.getUsername())
                .truename(sysAdmin.getTruename())
                .build();
    }


    /**
     * 校验密码是否正确
     *
     * @param user
     * @param password
     * @return
     */
    private Boolean checkPassword(SysAdmin user, String password) {
//        String encode = passwordEncoder.encode(password);
        return ENCODER.matches(password, user.getPassword());

    }


}
